#encoding:UTF-8
import mylib
import re
import MySQLdb
import pythonlibSB

conn = mylib.create_conn()

URL_TO_GET = "http://www.bongda.com.vn/article_contents.aspx?n_id="



def get_url_ketqua():
    try:
        url_time = mylib.get_date_today()
        url = get_url_chung(4)
        content = mylib.get_data(url)
        get_str = pythonlibSB.s_string(content,'id="ctl00_BD_cat_pnlDetailView"','div')
        pos1 = get_str.find('<tr')
        pos2 = get_str.find('</tr',pos1)
        get_str = get_str[pos1:pos2]
        reg = re.compile('(__showDetail)\((.*?)(\))')
        if reg.search(get_str):
            id_get = reg.search(get_str).group(2)
        
        last_url = URL_TO_GET + str(id_get)
        insert_url_ketqua(7, last_url, url_time)
        print "Xong"
    except:
        print "Loi roi"

def insert_url_ketqua(id_giai,url_giai,url_time):
    try:
        cmd = "CALL insert_url_ketqua('%s','%s','%s')"%(id_giai,url_giai,url_time)
        print cmd
        cursor = conn.cursor(MySQLdb.cursors.DictCursor)
        cursor.execute(cmd)
        cursor.close()
        print "insert thanh cong"
    except:
        print "Loi insert"
        
        

def get_url_chung(id_urltype):
    try:
        cmd = "SELECT `url` FROM `tbl_urltoget` WHERE id_urltype = '%s';"%id_urltype
        urls = mylib.get_result_sql(conn, cmd)
        return urls[0]['url']
    except:
        return ''

if __name__ == "__main__":
    get_url_ketqua()